package com.ucode.application.controller.crm;

import java.util.List;
import javax.validation.constraints.Size;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ucode.application.form.crm.ContactsForm;
import com.ucode.application.helper.CrmDataPermissionVerifier;
import com.ucode.application.security.CurrentLoginUserService;
import com.ucode.crm.dictionary.CrmResultDefineMsg;
import com.ucode.crm.dictionary.ModuleType;
import com.ucode.crm.mode.Contacts;
import com.ucode.crm.mode.Customer;
import com.ucode.crm.service.ContactsService;
import com.ucode.crm.service.CustomerService;
import com.ucode.crm.service.FollowupTeamUserService;
import com.ucode.crm.vo.ContactsVo;
import com.ucode.search.crm.model.ESContacts;
import com.ucode.search.crm.service.ESContactsService;
import com.ucode.springboot.starter.web.validator.group.AddGroup;
import com.ucode.tool.base.Paginator;
import com.ucode.tool.base.ResponseResult;
import com.ucode.tool.base.ResultCodeEnum;
import com.ucode.tool.exception.UcodeServiceException;
import cn.hutool.core.collection.CollUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags="CRM-联系人")
@RestController
@RequestMapping("/crm-contacts")
@Validated
public class ContactsController {
    private static final String moduleCode = "crm-contacts";
    
    @Autowired
    private CustomerService customerService;
    @Autowired
    private ContactsService contactsService;
    @Autowired
    private FollowupTeamUserService followupTeamUserService;
    @Autowired
    private CurrentLoginUserService currentLoginUserService;
    @Autowired
    private CrmDataPermissionVerifier dataPermissionVerifier;
    @Autowired
    private ESContactsService esContactsService;

    @PreAuthorize("hasAuthority('crm:contacts:list') or hasRole('ADMIN')")
    @ApiOperation("联系人列表")
    @GetMapping(value = "/list")
    public ResponseResult<Object> list(
            @ApiParam(value ="联系人名称/电话/手机号")  @RequestParam(value = "keywords") String keyword,
            @ApiParam(value ="用户(最多20人)")  @Size(max = 20,message="一次最多选择20人")@RequestParam(value = "userIds") List<Long> userIds,
            @ApiParam(value ="用户参与角色(0->全部,1->负责的2->参与的)",example="0")  @RequestParam(value = "prole", defaultValue = "0") Integer prole,
            @ApiParam(value="页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @ApiParam(value="每页记录数",example="20") @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize){
        
        userIds = dataPermissionVerifier.getCheckCurrentUserManageUsersByRead(moduleCode, userIds);
        
        try {
            Paginator<ESContacts> paginator = esContactsService.searchByUser(userIds, prole, keyword, pageNum, pageSize);
            return ResponseResult.success(paginator);
        } catch (Exception e) {
            throw new UcodeServiceException(ResultCodeEnum.SERVER_ERROR);
        }
    }
    
    
    @PreAuthorize("hasAuthority('crm:contacts:detail') or hasRole('ADMIN')")
    @ApiOperation(value="根据主键查询")
    @ApiImplicitParam(name = "id", value = "主键ID", required = true, dataType = "String",paramType = "path")
    @GetMapping("/getById/{id}")
    public ResponseResult<Object> getById(@PathVariable(name="id",required=true) Long id){
        
        Contacts contacts = contactsService.findById(id);
        if(contacts == null || contacts.getDeltag() == 1){
            throw new UcodeServiceException(ResultCodeEnum.NO_RECORD.code,"联系人已删除");
        }
        
        Integer power = null;
        if(contacts.getOwnerUserId() == null || contacts.getOwnerUserId().equals(0)){
            power = dataPermissionVerifier.getCurrentUserPowerByBusinessData(moduleCode, ModuleType.contacts, contacts.getId());
        }
        
        return ResponseResult.success(contacts);
    }
    
    
    @PreAuthorize("hasAuthority('crm:contacts:edit') or hasRole('ADMIN')")
    @ApiOperation(value="创建")
    @PostMapping("/create")
    public ResponseResult<Object> create(@Validated({AddGroup.class}) @RequestBody ContactsForm form) {
        Customer customer = customerService.findById(form.getCustomerId());
        if(customer == null || customer.getDeltag() == 1){
            throw new UcodeServiceException(ResultCodeEnum.NO_RECORD.code,CrmResultDefineMsg.contacts_add_customer_deleted_error);
        }
        
        if(customer == null || customer.getOwnerUserId().equals(0)){
            throw new UcodeServiceException(ResultCodeEnum.FAILED.code,CrmResultDefineMsg.customer_pool_add_contacts_error);
        }
        
        //添加客户联系人需要校验当前用户对客户数据的编辑权限
        dataPermissionVerifier.checkCurrentUserWritePowerByBusinessData(moduleCode, ModuleType.customer, customer.getId(), customer.getOwnerUserId(), CrmResultDefineMsg.contacts_add_permission_error);
        
        Long currentUserId = currentLoginUserService.getCurrentUserId();
        
        ContactsVo contactsVo = new ContactsVo(customer.getId(), 1, form.getName(), form.getMobile(), form.getTelephone(), form.getEmail(), form.getWechat(), form.getQq(), form.getDm(), form.getJob(), form.getBirthday(), form.getSex(), form.getAddress(), form.getRemark(), currentUserId,form.getShareType(), currentUserId,form.getTeamUserIds());
        Contacts contacts = contactsService.insert(contactsVo);
        
        return ResponseResult.success(contacts);
    }
    
    
    @PreAuthorize("hasAuthority('crm:contacts:edit') or hasRole('ADMIN')")
    @ApiOperation(value="更新")
    @ApiImplicitParam(name = "id", value = "联系人ID", required = true, dataType = "String",paramType = "path")
    @PostMapping("/update/{id}")
    public ResponseResult<Object> update(@PathVariable(name="id",required=true) Long id,
            @Validated({AddGroup.class}) @RequestBody ContactsForm form) {
        
        Contacts dbcontacts = contactsService.findById(id);
        if(dbcontacts == null || dbcontacts.getDeltag() == 1){
            throw new UcodeServiceException(ResultCodeEnum.NO_RECORD);
        }
        
        //校验权限
        dataPermissionVerifier.checkCurrentUserWritePowerByBusinessData(moduleCode, ModuleType.contacts, dbcontacts.getId(), dbcontacts.getOwnerUserId(), CrmResultDefineMsg.contacts_edit_permission_error,dbcontacts.getName());
        
        Contacts contacts = new Contacts(id,form.getName(), form.getMobile(), form.getTelephone(), form.getEmail(), form.getWechat(), form.getQq(), form.getDm(), form.getJob(), form.getBirthday(), form.getSex(), form.getAddress(), form.getRemark());
        
        int i = contactsService.update(contacts);
        
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }
    
    @PreAuthorize("hasAuthority('crm:contacts:delete') or hasRole('ADMIN')")
    @ApiOperation(value="删除联系人")
    @PostMapping("/delete")
    public ResponseResult<Object> delete(
            @ApiParam(value="联系人Ids",required=true) @Size(min = 1,max=20,message="一次能操作1-20条记录")@RequestParam(value = "ids", required=true) List<Long> ids) {
        
        List<Contacts> contactsList = contactsService.findByIds(ids);
        if(CollUtil.isNotEmpty(contactsList)){
            List<Long> manageUsers = dataPermissionVerifier.getCurrentUserManageUsers(moduleCode, 1);
             for(Contacts contacts : contactsList){
                Long ownerUserId = contacts.getOwnerUserId();
                if(contacts.getDeltag() == 1)
                    continue;
                
                if(ownerUserId == null || ownerUserId.equals(0))
                    throw new UcodeServiceException(ResultCodeEnum.FAILED.code,CrmResultDefineMsg.contacts_delete_permission_error,contacts.getName());
                
                if(contacts.getDc() == 0)
                    throw new UcodeServiceException(ResultCodeEnum.FAILED.code,CrmResultDefineMsg.contacts_dc_delete_error,contacts.getName());
                
                //校验权限
                dataPermissionVerifier.checkCurrentUserWritePowerByBusinessData(manageUsers, ModuleType.customer, contacts.getId(), ownerUserId, CrmResultDefineMsg.contacts_delete_permission_error, contacts.getName());
                contactsService.deleteByLogic(contacts.getId());
            }
        }
        return ResponseResult.success();
        
    }
    
    @PreAuthorize("hasAuthority('crm:contacts:edit') or hasRole('ADMIN')")
    @ApiOperation(value="设置首要联系人")
    @ApiImplicitParam(name = "id", value = "联系人ID", required = true, dataType = "String",paramType = "path")
    @PostMapping("/setDc/{id}")
    public ResponseResult<Object> setDc(@PathVariable(name="id",required=true) Long id) {
        
        Contacts dbcontacts = contactsService.findById(id);
        if(dbcontacts == null || dbcontacts.getDeltag() == 1){
            throw new UcodeServiceException(ResultCodeEnum.NO_RECORD);
        }
        //校验客户写权限
        dataPermissionVerifier.checkCurrentUserWritePowerByBusinessData(moduleCode, ModuleType.customer, dbcontacts.getCustomerId(), dbcontacts.getOwnerUserId(), CrmResultDefineMsg.contacts_edit_permission_error,dbcontacts.getName());
        
        int i = contactsService.updateDc(id);
    
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    
    }
    
    @PreAuthorize("hasAuthority('crm:contacts:edit') or hasRole('ADMIN')")
    @ApiOperation(value="指定联系人共享人")
    @ApiImplicitParam(name = "id", value = "联系人ID", required = true, dataType = "String",paramType = "path")
    @PostMapping("/updateShareType/{id}")
    public ResponseResult<Object> updateShareType(@PathVariable(name="id",required=true) Long id,
            @ApiParam(value="联系人共享类型:0负责人专享1指定人共享2团队共享",required=true,example="0") @RequestParam(value = "shareType", required=true)Integer shareType, 
            @ApiParam(value="共享用户(指定人共享时填写)",required=false) @Size(max=2,message="最多指定2人")@RequestParam(value = "teamUsers", required=false) List<Long> teamUsers) {
        
        Contacts dbcontacts = contactsService.findById(id);
        if(dbcontacts == null || dbcontacts.getDeltag() == 1){
            throw new UcodeServiceException(ResultCodeEnum.NO_RECORD);
        }
        //校验客户写权限
        dataPermissionVerifier.checkCurrentUserWritePowerByBusinessData(moduleCode, ModuleType.customer, dbcontacts.getCustomerId(), dbcontacts.getOwnerUserId(), CrmResultDefineMsg.contacts_edit_permission_error,dbcontacts.getName());
        
        int i = contactsService.updateShareType(id, shareType, teamUsers);
    
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }
    
    
}
